package cn.sdnu.database.service;

import cn.sdnu.database.controller.DbController;
import cn.sdnu.database.utils.Utils;

import java.io.File;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Master_Joe qiaoguangtong@aliyun.com
 */
public class Drop {
	private static Drop drop = null;
	private static ReentrantLock lock = new ReentrantLock();

	private Drop() {

	}

	public static Drop getInstance() {
		if (drop == null) {
			lock.lock();
			try {
				if (drop == null) {
					drop = new Drop();
				}
			} finally {
				lock.unlock();
			}
		}
		return drop;
	}

	public void sqlHandle(String sql) {
		if (sql.startsWith("drop table ")) {
			if (Use.getInstance().getDatabaseUsed() != null) {
				dropTable(sql);
			} else {
				System.out.println("ERROR: No database selected");
			}
		} else if (sql.startsWith("drop database ")) {
			// Can't drop database 'db'; database doesn't exist
			dropDatabase(sql);
		} else {
			System.out.println("Error: You have some syntax error, please try again");
		}
	}

	/**
	 * 删除表
	 * 
	 * @param sql
	 */
	private void dropTable(String sql) {
		String tableName = sql.substring(11, sql.length() - 2);
		List<String> tables = Utils.getTables(Use.getInstance().getDatabaseUsed());

		if (tables.contains(tableName)) {
			String path = DbController.TEST_BASE + Use.getInstance().getDatabaseUsed() + File.separator + tableName
					+ DbController.EXTENSION;
			boolean deleteFile = Utils.deleteFile(path);
			if (!deleteFile) {
				System.err.println("System error, exit");
				System.exit(0);
			} else {
				System.out.println("Query OK, 0 rows affected");
			}
		} else {
			System.out.println("ERROR : Unknown table '" + Use.getInstance().getDatabaseUsed() + "." + tableName + "'");
		}
	}

	/**
	 *
	 * @param sql
	 */
	private void dropDatabase(String sql) {
		String dbName = sql.substring(14, sql.length() - 2);
		String filePath = Utils.getDatabasePath(dbName);
		File file = new File(filePath);
		if (file.isDirectory() && file.exists()) {
			boolean deleteFile = Utils.delFile(file);
			if (deleteFile) {
				System.out.println("Query OK, 1 row affected");
			} else {
				System.err.println("System error, exit");
				System.exit(0);
			}
		} else {
			System.out.println("Error: Can't drop database '" + dbName + "'; database doesn't exist");
		}
	}
}
